package com.ljb.android.component.search.view.act

import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SizeUtils
import com.ljb.android.comm.adapter.decoration.RVItemDecorationMargin
import com.ljb.android.comm.adapter.ktx.addDataAndLast
import com.ljb.android.comm.mvp.CommMvpActivity
import com.ljb.android.comm.router.core.RouterManager
import com.ljb.android.comm.weiget.page.PageState
import com.ljb.android.component.search.R
import com.ljb.android.component.search.adapter.SearchListAdapter
import com.ljb.android.component.search.bean.SearchBean
import com.ljb.android.component.search.contract.SearchContract
import com.ljb.android.component.search.databinding.SearchActivityMainBinding
import com.ljb.android.component.search.databinding.SearchLayoutTitlebarBinding
import com.ljb.android.component.search.presenter.SearchPresenter
import com.ljb.android.component.search.router.SearchRouter

/**
 * @Author Kotlin MVP Plugin
 * @Date 2021/05/30
 * @Description input description
 **/
@Route(path = SearchRouter.Activity.SEARCH_MAIN)
class SearchActivity : CommMvpActivity<SearchContract.IPresenter, SearchActivityMainBinding>(),
    SearchContract.IView {

    companion object {
        const val KEY_WORD = "key"
    }

    private lateinit var mBindTitle: SearchLayoutTitlebarBinding
    private var mPage = 0
    private var mKey = ""

    private val mListAdapter = SearchListAdapter()

    override fun registerPresenter() = SearchPresenter::class.java

    override fun getLayoutId() = R.layout.search_activity_main

    override fun registerBinding(
        layoutInflater: LayoutInflater,
        parent: ViewGroup
    ): SearchActivityMainBinding {
        return SearchActivityMainBinding.inflate(layoutInflater, parent, false)
    }

    override fun supportSwipeBack() = true

    override fun supportLoadMore() = true

    override fun supportTitle() = true

    override fun supportDraw() = true

    override fun supportPage() = true

    override fun customTitleView(layoutInflater: LayoutInflater, viewGroup: ViewGroup): View {
        mBindTitle = SearchLayoutTitlebarBinding.inflate(layoutInflater, viewGroup, false)
        return mBindTitle.root
    }

    override fun init(savedInstanceState: Bundle?) {
        mKey = intent.getStringExtra(KEY_WORD) ?: ""
    }

    override fun initView() {
        initTitleView()
        initPageView()
        initRecyclerView()
        setEnableLoadMore(false)
    }

    private fun initTitleView() {
        mBindTitle.ivToolbarLeft.setOnClickListener { onBackPressed() }
        mBindTitle.tvToolbarRight.setOnClickListener { doSearch() }
        mBindTitle.etSearch.apply {
            addTextChangedListener {
                if (it.isNullOrEmpty()) {
                    mBindTitle.ivClear.visibility = View.GONE
                } else {
                    mBindTitle.ivClear.visibility = View.VISIBLE
                }
            }
            setOnEditorActionListener { _, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEND
                    || actionId == EditorInfo.IME_ACTION_SEARCH
                    || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)
                ) {
                    doSearch()
                    true
                } else {
                    false
                }
            }
        }
        mBindTitle.ivClear.setOnClickListener {
            clearText()
        }

    }

    private fun initPageView() {
        mPageLayout?.setEmptyView(R.layout.search_layout_search_empty)
    }

    private fun initRecyclerView() {
        mBind.rvList.apply {
            layoutManager = LinearLayoutManager(this@SearchActivity)
            adapter = mListAdapter
            mListAdapter.setOnItemClickListener { _, _, position ->
                val url = mListAdapter.data[position].link
                goWebView(url)
            }
            addItemDecoration(
                RVItemDecorationMargin(
                    bottom = SizeUtils.dp2px(10f),
                    onlyLastItem = true
                )
            )
        }
    }

    override fun initData() {
        if (!TextUtils.isEmpty(mKey)) {
            mBindTitle.etSearch.setText(mKey)
            doSearch()
        }
    }

    override fun onLoadMore() {
        getPresenter().doSearch(mPage, mKey)
    }

    override fun onSearchResult(searchBean: SearchBean) {
        setEnableLoadMore(true)
        if (mPage == 0) {
            mListAdapter.data.clear()
            mListAdapter.notifyDataSetChanged()
            if (searchBean.data.datas.isNullOrEmpty()) {
                //无搜索结果
                setPage(PageState.STATE_EMPTY)
                return
            }
            setPage(PageState.STATE_SUCCESS)
        } else {
            finishLoadMore(true)
        }

        if (searchBean.data.datas.isEmpty()) {
            //没有更多数据
            setNoLoadMore()
        } else {
            mListAdapter.addDataAndLast(searchBean.data.datas)
            mPage++
        }

    }

    private fun clearText() {
        mBindTitle.etSearch.setText("")
        mListAdapter.data.clear()
        mListAdapter.notifyDataSetChanged()
    }

    private fun goWebView(url: String) {
        RouterManager.goWeb(url)
    }

    private fun doSearch() {
        setNoLoadMore(false)
        mPage = 0
        mKey = mBindTitle.etSearch.text.toString().trim()
        getPresenter().doSearch(mPage, mKey)
    }

}
